﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Linq;
using UnityEngine.SceneManagement;
using GersonFrame.Tool;

namespace GersonFrame.ABFrame
{

    public class LoadingScene : MonoBehaviour
    {
 

        public GameObject m_TipPackage;
        public GameObject m_LoadingPage;
        public Text m_tipText;
        public Button m_confirmBtn;
        public Button m_cancelBtn;
        /// <summary>
        /// 最上层提示信息
        /// </summary>
        public Text m_TopTip;

        public Slider m_Slider;
        public Text m_progresstext;

        private float m_preloadProgress = 0;
        private float m_sumTime = 0;

        /// <summary>
        /// 预加载数量
        /// </summary>
        private int m_preloadCount = 0;
        /// <summary>
        /// 预加载资源信息
        /// </summary>
        private Dictionary<string, int> m_PreloadInfoDIc = new Dictionary<string, int>();

        void Start()
        {
            CheckAssetUpdate();
        }

        #region 热更检查

        void CheckAssetUpdate()
        {
            HotPatchManager.Instance.Init(this);
            HotPatchManager.Instance.ServerInfoErrorCallBack += SerInfoError;
            HotPatchManager.Instance.DownLoadItemErrorCallBack += DownLoadError;

            if (HotPatchManager.Instance.ComputeUnPackFile())
            {
                this.m_LoadingPage.Hide();
                this.m_TipPackage.Hide();
                m_TopTip.text = "资源解压中...";
                HotPatchManager.Instance.StartUnPackFile(HotFix);
            }
            else HotFix();


        }


        void HotFix()
        {
            m_sumTime = 0;
            //1 检查网络环境
            if (Application.internetReachability == NetworkReachability.NotReachable)
            {
                m_TopTip.text = "网络连接失败!请检查网络连接是否正常?";
            }
            else
            {
                //检查版本
                CheckVersion();
            }
        }
        void CheckVersion()
        {
            m_confirmBtn.onClick.RemoveAllListeners();
            m_cancelBtn.onClick.RemoveAllListeners();
            HotPatchManager.Instance.CheckVersion((hot) =>
            {
                if (hot)
                {
                    this.m_LoadingPage.Hide();
                    this.m_TipPackage.Show();
                    this.m_TopTip.gameObject.Hide();
                    this.m_tipText.text = string.Format("当前版本为{0},有{1:F}M大小热更包,是否确定下载?", HotPatchManager.Instance.CurrentVersion, HotPatchManager.Instance.LoadSumSize / 1024.0f);
                    m_confirmBtn.onClick.AddListener(this.OnConfirmBtnClick);
                    m_cancelBtn.onClick.AddListener(this.OnCancelBtnClick);
                }
                //不需要热更
                else
                {
                    this.m_LoadingPage.Show();
                    this.m_TipPackage.Hide();
                    this.m_TopTip.gameObject.Hide();
                    //进入游戏
                    this.OnHotPathDownLoadFinish();
                }
            }
                );
        }

        void OnConfirmBtnClick()
        {
            m_confirmBtn.onClick.RemoveAllListeners();
            m_cancelBtn.onClick.RemoveAllListeners();
            if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android)
            {
                //检测是否是在移动网络下面 电信局要求
                if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)//手机数据网络
                {
                    this.m_tipText.text = string.Format("当前使用手机流量,是否继续下载?", HotPatchManager.Instance.CurrentVersion, HotPatchManager.Instance.LoadSumSize / 1024.0f);
                    m_confirmBtn.onClick.AddListener(this.StartDownPatch);
                    m_cancelBtn.onClick.AddListener(this.OnCancelBtnClick);
                }
                else
                    StartDownPatch();
            }
            else StartDownPatch();

        }

        /// <summary>
        /// 正式开始下载补丁包
        /// </summary>
        void StartDownPatch()
        {
            m_sumTime = 0;
            this.m_TipPackage.Hide();
            this.m_LoadingPage.Show();
            StartCoroutine(HotPatchManager.Instance.StartDownLoadAB(OnHotPathDownLoadFinish));

        }
        void OnCancelBtnClick()
        {
            Application.Quit();
        }

        /// <summary>
        /// 热更下载完毕 或者没有资源要下载
        /// </summary>
        void OnHotPathDownLoadFinish()
        {
            Debug.Log("补丁下载完毕");
            PreLoad();
        }
        private void DownLoadError(string all)
        {
            this.m_tipText.text = string.Format("{0}等资源下载失败，请尝试重新下载!", all);
        }

        private void SerInfoError()
        {
            this.m_tipText.text = "服务器列表获取失败，请检查网络是否链接正常?尝试重新下载";
        }

        #endregion
        public void PreLoad()
        {
#if UNITY_EDITOR
            MyDebuger.InitLogger();
#endif
            ABManager.Instance.LoadAssetBundleConfig();
            ResourceManager.Instance.Init();
            ObjectManager.Instance.Init();
            m_PreloadInfoDIc.Clear();
            AssetLoadConfig assetLoadConfig = ResourceManager.Instance.LoadResource<AssetLoadConfig>(ABFrameConfigGeter.ABPreLoadConfigPath);
            AddMobilePreLoadFile(assetLoadConfig);
            StartCoroutine(this.PreLoadAssets());
        }

        void AddEditorPreLoadFile(AssetLoadConfig assetLoadConfig)
        {
            for (int i = 0; i < assetLoadConfig.m_PreLoadInfo.Count; i++)
            {
                PreLoadFloderInfo preassetfloderInfo = assetLoadConfig.m_PreLoadInfo[i];
                string assetfloder = "";
                if (preassetfloderInfo.PreLoadFloderPath.Contains("Assets/"))
                {
                    assetfloder = preassetfloderInfo.PreLoadFloderPath.Replace("Assets/", "");
                }
                string floderptah = Application.dataPath + "/" + assetfloder;

                if (Directory.Exists(floderptah))
                {
                    DirectoryInfo dir = Directory.CreateDirectory(floderptah);
                    FileInfo[] files = dir.GetFiles();
                    for (int j = 0; j < files.Length; j++)
                    {
                        if (files[j].Name.EndsWith(".prefab"))
                        {
                            m_PreloadInfoDIc.Add("Assets/" + assetfloder + "/" + files[j].Name, preassetfloderInfo.PreLoadCount);
                        }
                    }
                }
            }
        }

        void AddMobilePreLoadFile(AssetLoadConfig assetLoadConfig)
        {
            AssetBundleConfig config = ABManager.Instance.ABConfig;
            for (int i = 0; i < config.ABList.Count; i++)
            {
                for (int j = 0; j < assetLoadConfig.m_PreLoadInfo.Count; j++)
                {
                    PreLoadFloderInfo preloadInfo = assetLoadConfig.m_PreLoadInfo[j];
                    int index = config.ABList[i].Path.LastIndexOf(preloadInfo.PreLoadFloderPath);
                    int count = preloadInfo.PreLoadFloderPath.Length;
                    if (config.ABList[i].Path.Length > count && index >= 0 && config.ABList[i].Path.Substring(index + count, 1) == "/")
                    {
                        if (m_PreloadInfoDIc.ContainsKey(config.ABList[i].Path))
                            MyDebuger.LogError(string.Format("资源重复 {0}", config.ABList[i].Path));
                        else
                            m_PreloadInfoDIc.Add(config.ABList[i].Path, preloadInfo.PreLoadCount);
                    }
                }
            }
        }

        private WaitForFixedUpdate wait = new WaitForFixedUpdate();

        /// <summary>
        /// 开始预加载
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        IEnumerator PreLoadAssets()
        {
            List<string> keys = m_PreloadInfoDIc.Keys.ToList();
            m_preloadCount = 0;
            while (m_preloadCount < keys.Count)
            {
                string loadPath = keys[m_preloadCount];
                int preloadcount = m_PreloadInfoDIc[loadPath];
                ObjectManager.Instance.PreLoadGameobject(loadPath, preloadcount);
                m_preloadProgress = m_preloadCount * 1f / keys.Count;
                m_preloadCount++;
                m_progresstext.text = string.Format("{0:f0}%", m_preloadProgress * 100);
                this.m_Slider.value = m_preloadProgress / 1;
                yield return wait;
            }
            m_preloadCount = 0;
            m_preloadProgress = 1;
            m_PreloadInfoDIc.Clear();
            SceneManager.LoadSceneAsync("Main", LoadSceneMode.Single);
        }

        private void Update()
        {
            if (HotPatchManager.Instance.StartUnPack)
            {
                m_sumTime += Time.deltaTime;
                float speed = (HotPatchManager.Instance.AlreadyUnPackSumSize / 1024.0f) / this.m_sumTime;
                m_progresstext.text = string.Format("{0:F} M/S", speed);
                this.m_Slider.value = HotPatchManager.Instance.GetUnPackProgress();
            }

            if (HotPatchManager.Instance.StartDownLoad)
            {
                m_sumTime += Time.deltaTime;
                float speed = (HotPatchManager.Instance.GetLoadSize() / 1024.0f) / this.m_sumTime;
                m_progresstext.text = string.Format("{0:F} M/S", speed);
                this.m_Slider.value = HotPatchManager.Instance.GetProgress();
            }
        }

    }



}
